#include <stdio.h>

#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "hi_io.h"
#include "hi_pwm.h"
#include "hi_gpio.h"

#define DELAY_20MS 20*1000
#define PWM_FREQ 1000

#define LED_PORT HI_GPIO_IDX_9

static void *PWMTask(const char *arg)
{
    (void)arg;

    uint16_t pwm_duty = 0;
    /** Initialize GPIO as LED connection **/
    hi_gpio_init();
    
    /** Set the function of GPIO 09 to PWM port 0**/
    hi_io_set_func(LED_PORT, HI_IO_FUNC_GPIO_9_PWM0_OUT);
    /** Initialize PWM port to 0 **/
    hi_pwm_init(HI_PWM_PORT_PWM0);

    while(1){
        pwm_duty = pwm_duty + 10;
        if(pwm_duty > 1000){
            pwm_duty = 0;
        }
        /** Set PWM output tp PWM port 0  **/
        hi_pwm_start(HI_PWM_PORT_PWM0, pwm_duty, PWM_FREQ);
        /** Compute duty ratio  **/
        printf("pwm_duty_ratio:%f\n", pwm_duty * 1.0f / PWM_FREQ);
        usleep(DELAY_20MS);
    }

    return NULL;
}

static void PWMTaskEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "PWMTask";         
    attr.attr_bits = 0U;            
    attr.cb_mem = NULL;             
    attr.cb_size = 0U;              
    attr.stack_mem = NULL;          
    attr.stack_size = 4096;         
    attr.priority = 11;             

    if (osThreadNew((osThreadFunc_t)PWMTask, NULL, &attr) == NULL) {
        printf("[PWMTaskEntry] Failed to create PWMTask!\n");
    }
}

SYS_RUN(PWMTaskEntry);
